package org.projects.graduates.domain;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.builder.HashCodeBuilder;

import com.dayatang.domain.AbstractEntity;
import com.dayatang.domain.QuerySettings;

@Entity
@Table(name = "studyings")
public class Studying extends AbstractEntity {

	private static final long serialVersionUID = 5247383090537582123L;

	@OneToOne
	@NotNull
	private Person person;
	@OneToOne
	@NotNull
	private Course course;

	public Studying() {
		super();
	}

	public Studying(Person person, Course course) {
		super();
		this.person = person;
		this.course = course;
	}

	public static Set<Person> findStudentOf(Course course) {
		Set<Person> results = new HashSet<Person>();
		QuerySettings<Studying> settings = QuerySettings.create(Studying.class).eq("course", course);
		for (Studying stu : getRepository().find(settings)) {
			results.add(stu.getPerson());
		}
		return results;
	}

	public static List<Studying> findBy(Person person) {
		List<Studying> results = new ArrayList<Studying>();

		QuerySettings<Studying> settings = QuerySettings.create(Studying.class).eq("person", person);
		results.addAll(getRepository().find(settings));
		return results;
	}

	public static List<Course> allCourseOf(Person person) {
		List<Course> results = new ArrayList<Course>();
		List<Studying> studyings = new ArrayList<Studying>();
		QuerySettings<Studying> settings = QuerySettings.create(Studying.class).eq("person", person);
		studyings.addAll(getRepository().find(settings));
		for (Studying study : studyings) {
			if (null != study.getCourse()) {
				results.add(study.getCourse());
			}
		}

		return results;
	}

	public boolean equals(Object other) {
		if (null == other) {
			return false;
		}
		if (other instanceof Studying) {
			Studying o = (Studying) other;
			if (o.getId() == this.getId()) {
				return true;
			}
		}
		return false;
	}

	public int hashCode() {
		return new HashCodeBuilder(17, 37).append(this.getId()).toHashCode();
	}

	@Override
	public String toString() {
		return person.getShowName() + " study " + course.getName();
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public Course getCourse() {
		return course;
	}

	public void setCourse(Course course) {
		this.course = course;
	}

}
